package com.wemew.securityapi.config.security.filter;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wemew.common.entity.User;
import com.wemew.common.enums.error.Error;
import com.wemew.common.enums.password.PassWordEnum;
import com.wemew.common.exceptionhandler.GuliException;
import com.wemew.common.redis.UserRedis;
import com.wemew.common.utils.R;
import com.wemew.common.utils.ResponseUtil;
import com.wemew.securityapi.config.security.config.TokenManager;
import com.wemew.securityapi.entity.SecurityUser;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
   * 作者 CG
   * 时间 2021/1/13 21:06
   * 注释 登录拦截器
   */

public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
    private TokenManager tokenManager;
    private AuthenticationManager authenticationManager;
    private UserRedis userRedis;

    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager,UserRedis userRedis) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.userRedis = userRedis;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login","POST"));
    }

    //1 获取表单提交用户名和密码
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        //获取表单提交数据
        try {
            User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
            String username = user.getUsername();
            if (StrUtil.isBlank(username)){
                throw new AuthenticationServiceException("",new GuliException(Error.Error4003));
            }
            String password = user.getPassword();
            if (StrUtil.isBlank(password)){
                throw new AuthenticationServiceException("",new GuliException(Error.Error4004));
            }
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username,password,
                    new ArrayList<>()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new AuthenticationServiceException("", new GuliException(Error.Error4002));
        }
    }

    //2 认证成功调用的方法
    @Override
    protected void successfulAuthentication(HttpServletRequest request, 
                                            HttpServletResponse response, FilterChain chain, Authentication authResult)
            throws IOException, ServletException {
        //认证成功，得到认证成功之后用户信息
        SecurityUser user = (SecurityUser)authResult.getPrincipal();
        //根据用户名生成token
        String code = RandomUtil.randomString(6);
        String token = tokenManager.createToken(user.getCurrentUserInfo().getUsername(),code);
        //把用户名称和用户权限列表放到redis
        userRedis.addPermissions(user.getCurrentUserInfo().getUsername(),user.getPermissionValueList());
        userRedis.addTokenCode(user.getCurrentUserInfo().getUsername(),code);
        //返回token
        ResponseUtil.out(response,new R("token",token));
    }

    //3 认证失败调用的方法
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed)
            throws IOException, ServletException {
        if (failed instanceof UsernameNotFoundException){
            ResponseUtil.out(response, new R(failed.getCause()));
        }else if(failed instanceof BadCredentialsException){
            ResponseUtil.out(response, new R(Error.Error4005));
        }else {
            ResponseUtil.out(response, new R(failed));
        }
    }
}
